package com.wuwei.tms.workbench.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.tms.exception.TmsException;
import com.wuwei.tms.pojo.Borrow;
import com.wuwei.tms.pojo.User;
import com.wuwei.tms.setting.mapper.UserMapper;
import com.wuwei.tms.utils.result.Result;
import com.wuwei.tms.utils.token.TokenUtil;
import com.wuwei.tms.vo.BorrowExcel;
import com.wuwei.tms.vo.BorrowPrint;
import com.wuwei.tms.vo.BorrowVo;
import com.wuwei.tms.workbench.mapper.BorrowMapper;
import com.wuwei.tms.workbench.service.BorrowService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * RequestMapping中，visitor是游客页面访问的请求
 */
@RequestMapping("/T01/borrow")
@RestController
//@CrossOrigin
public class BorrowController {

    @Resource
    private BorrowService borrowService;

    @Resource
    private BorrowMapper borrowMapper;

    /**
     * 借还操作的方法，借还就是通过该方法进行操作
     * @param borrowVo
     * @param request
     * @return
     */
    @PostMapping("borrowAndReturn")
    public Result<String> borrowAndReturn(@RequestBody BorrowVo borrowVo , HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        Long operator = TokenUtil.getEmpnoFromToken(token);
        return borrowService.borrowAndReturn(borrowVo, operator);
    }

    @GetMapping("list/{currentPage}/{pageSize}/{search}")
    /**
     * 得到所有的借用记录传给前端
     */
    public Result<List<Borrow>> list (@PathVariable("currentPage") Integer currentPage , @PathVariable("pageSize") Integer pageSize, @PathVariable ("search") String search) {
        List<Borrow> records= borrowService.listAndPagination(currentPage, pageSize, search);
        return Result.ok(records);
    }


    @GetMapping("total/{search}")
    /**
     * 得到所有的飞机传给前端
     */
    public Result<Long> total (@PathVariable ("search") String search){
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(search!=null,Borrow::getBorrowById,search);
        Long count = borrowMapper.selectCount(queryWrapper);
        return Result.ok(count);
    }

    /**
     * 找到borrow表中和该飞机和该员工有关的所有数据
     */
    @GetMapping("unreturned/{currentPage}/{pageSize}/{empno}/{airplane}")
    public Result<List<BorrowExcel>> unreturned (@PathVariable("currentPage") Integer currentPage , @PathVariable("pageSize") Integer pageSize,
                                            @PathVariable ("empno") Long empno,@PathVariable ("airplane") String airplane) {
        List<BorrowExcel> records = borrowService.unReturnedPage(currentPage,pageSize,empno,airplane);
        return Result.ok(records);
    }

    /**
     * 找到borrow表中和该飞机和该员工有关的所有数据
     */
    @GetMapping("unreturnedTotal/{empno}/{airplane}")
    public Result<Long> unreturnedTotal (@PathVariable ("empno") Long empno,@PathVariable ("airplane") String airplane){
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper<>();
        if(empno==0&&"_".equals(airplane)){
            return Result.ok(0L);
        } else if (empno==0) {
            queryWrapper.eq(Borrow::getAirplaneId,airplane);
        } else if ("_".equals(airplane)) {
            queryWrapper.eq(Borrow::getBorrowById,empno);
        } else {
            queryWrapper.eq(Borrow::getAirplaneId,airplane).eq(Borrow::getBorrowById,empno);
        }
        Long count = borrowMapper.selectCount(queryWrapper);
        return Result.ok(count);
    }

    /**
     * 找到borrow表中和该飞机和该员工有关的所有数据
     */
    @GetMapping("download/{empno}/{airplane}")
    public void download (@PathVariable ("empno") Long empno, @PathVariable ("airplane") String airplane, HttpServletResponse response) {

        List<BorrowExcel> records = borrowService.downloadUnReturned(empno,airplane);
        //把数据写成excel
        String filename = "output.xlsx";
        EasyExcel.write(filename,BorrowExcel.class).sheet().doWrite(records);
        //将该文件返回给前端
        // 设置响应的内容类型为 Excel

        // 设置响应头，告诉浏览器该文件以附件形式下载
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"output.xlsx\"");
        try(InputStream inputStream = new FileInputStream(filename);
            OutputStream outputStream = response.getOutputStream()){
            // 将文件的内容以流的形式写入响应对象
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Resource
    private UserMapper userMapper;

    /**
     * 获取用于打印的数据的方法
     * @param empno 工号
     * @return
     */
    @GetMapping("printForList/{empno}")
    public Result<List<BorrowPrint>> printForList(@PathVariable ("empno") Long empno){
        List<BorrowPrint> list = new ArrayList<>();
        if (empno==0) {
            return Result.ok(list);
        }else {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmpno,empno);
            User user = userMapper.selectOne(queryWrapper);
            if (user==null) {
                throw new TmsException(30011,"工号输入错误！");
            }
            List<BorrowPrint> returnList = borrowService.printForList(empno);
            returnList.forEach(b->b.setName(user.getName()));
            return Result.ok(returnList);
        }
    }

}
